/*
司机数据提交窗口
*/

angular.module("driver").controller("driverinfoCtrl", ['$scope', '$meteor', '$rootScope', '$state', '$ionicPopup', 'Map', 'Upload', '$ionicLoading', 'IMGSERVER', 'FileUploader', '$cordovaImagePicker', '$cordovaFileTransfer',
  function($scope, $meteor, $rootScope, $state, $ionicPopup, Map, Upload, $ionicLoading, IMGSERVER, FileUploader, $cordovaImagePicker, $cordovaFileTransfer){
		$scope.info = {
		};

    $scope.images = [{en: 'face', cn: '头像', src: null}, 
    {en: 'driving_license', cn: '驾驶证', src: null}, 
    {en: 'identity_card', cn: '身份证', src: null}];

		$scope.showAlert = function(title, temp) {
			var alertPopup = $ionicPopup.alert({
				title: title,
				template: temp,
        okType: 'button-royal',
        okText: '确定'
			});
			alertPopup.then(function(res) {
        $state.go('main.amap');
				//console.log('Thank you for not eating my delicious ice cream cone');
			});
		};

    $scope.show = function() {
      $ionicLoading.show({
        template: '<ion-spinner icon="ios"></ion-spinner>\
        <a>上传中...</a>'
      });
    };
    $scope.hide = function(){
      $ionicLoading.hide();
    };

    //$scope.user = Meteor.user();
    $meteor.subscribe('userData').then(function(subscriptionHandle){
      $scope.user = $meteor.object(Meteor.users, Meteor.userId());
    });

    //console.log($scope.user);
    $scope.upload = function (image) {
        //var _disId = disId;
        //console.log(image.files);
        if (image.file) {

          var file = image.file;
          var type = image.en;
          Resizer.resize(file, {width: 200, height: 200, cropSquare: true}, function(err, file) {
            $scope.show();
            Upload.upload({
                url: IMGSERVER.uploadurl,
                method: 'POST',
                //fileName: $scope.user.username + type,
                file: file
            }).progress(function (evt) {
                console.log(evt);
            }).success(function (data, status, headers, config) {
                var path = data;
                //console.log(path);
                $meteor.call('uploadImage', type, IMGSERVER.showurl + path);
                $scope.hide();
                image.file = null;
            });
          });
        }

    };

    $scope.finish = function () {
/*
      $scope.images.forEach(function (image) {
        $scope.upload(image);
      });
*/
      //console.log($scope.user.images);
      if (!$scope.user.images.face) {$scope.showAlert('资料缺失', '没有上传[大头照片]!'); return};
      if (!$scope.user.images.driving_license) {$scope.showAlert('资料缺失', '没有上传[驾照]!'); return};
      if (!$scope.user.images.identity_card) {$scope.showAlert('资料缺失', '没有上传[身份证]!'); return};

      Applys.insert({'userid': $scope.user._id, 'info': $scope.user.others, 'images': $scope.user.images, 'pass': false}, function (err) {
        //console.log(err);
        $scope.showAlert('提交成功', '我们将在2个工作日内审核');
        //$state.go('#');
      });
    };

    $scope.addImages = function (files, image) {
      if (files.length > 0) {
        image.file = files[0];
        $scope.upload(image);
      }
      /*
      console.log();
      if (files.length > 0) {
        var reader = new FileReader();

        reader.onload = function (e) {
          $scope.$apply(function() {
            image.src = e.target.result;
            $scope.myCroppedImage = '';
          })
        };
        image.files = files;
        reader.readAsDataURL(files[0]);
      }
      else {
        image.src = undefined;
      }
      */
    };
    $scope.uploader = new FileUploader();
    var uploader = $scope.uploader = new FileUploader({
      url: IMGSERVER.uploadurl
    });

    // FILTERS

    uploader.filters.push({
      name: 'imageFilter',
      fn: function(item /*{File|FileLikeObject}*/ , options) {
        var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
        return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
      }
    });

    // CALLBACKS

    uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/ , filter, options) {
      console.info('onWhenAddingFileFailed', item, filter, options);
    };
    uploader.onAfterAddingFile = function(fileItem) {
      console.info('onAfterAddingFile', fileItem);
      $scope.images[fileItem.num]._file = fileItem._file;
      fileItem.upload();
      $scope.show();
    };
    uploader.onAfterAddingAll = function(addedFileItems) {      
      console.info('onAfterAddingAll', addedFileItems);
    };
    uploader.onBeforeUploadItem = function(item) {
      console.info('onBeforeUploadItem', item);
    };
    uploader.onProgressItem = function(fileItem, progress) {
      console.info('onProgressItem', fileItem, progress);
    };
    uploader.onProgressAll = function(progress) {
      console.info('onProgressAll', progress);
    };
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
      console.info('onSuccessItem', fileItem, response, status, headers);
    };
    uploader.onErrorItem = function(fileItem, response, status, headers) {
      console.info('onErrorItem', fileItem, response, status, headers);
    };
    uploader.onCancelItem = function(fileItem, response, status, headers) {
      console.info('onCancelItem', fileItem, response, status, headers);
    };
    uploader.onCompleteItem = function(fileItem, response, status, headers) {
      console.info('onCompleteItem', fileItem, response, status, headers);
      $scope.selectedImage = false;
      $scope.uploader.queue.pop();
      $scope.hide();
      console.log();
      $meteor.call('uploadImage', $scope.images[fileItem.num].en, IMGSERVER.showurl + response);
      $scope.images[fileItem.num]._file = null;
    };
    uploader.onCompleteAll = function() {
      console.info('onCompleteAll');
    };

    //console.info('uploader', uploader);


    $scope.imagePicker = function(image) {
      var options = {
        maximumImagesCount: 1,
        quality: 80
      };

      $cordovaImagePicker.getPictures(options)
        .then(function(results) {
          console.log(results);
          if (results.length) {
            fileURL = results[0];
            $scope.show();
            $cordovaFileTransfer.upload(IMGSERVER.uploadurl, fileURL, {})
              .then(function(result) {
                //alert(JSON.stringify(result));
                $scope.hide();
                console.log(results);
                $meteor.call('uploadImage', image.en, IMGSERVER.showurl + result.response);
              }, function(err) {
                $scope.hide();
              }, function(progress) {
                //alert('progress')
              });
          }
        }, function(error) {
          alert('发生错误，请重试');
          // error getting photos
        });
    };

}]);
